package com.shimao.celnet.payment.controller;

import com.shimao.celnet.payment.model.ASysUser;
import com.shimao.celnet.payment.service.ASysPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * 用户登录
 * Created by ensure on 2017/4/21.
 */
@Controller
public class HomeController {
    @Autowired
    private ASysPermissionService resourcesService;

    @RequestMapping(value="/",method= RequestMethod.GET)
    public String login(){
        return "login";
    }

    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String loginInfo(){
        return "login";
    }

    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(@ModelAttribute ASysUser user, Model model){




        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getPassword());

        try {
            //取得用户权限菜单
            subject.login(token);
            Session session = subject.getSession();
            String userGuid = (String)session.getAttribute("userSessionId");
            model.addAttribute("menuData",resourcesService.getMenu(userGuid));
            return "index";
        }catch (LockedAccountException lae) {
            token.clear();
            model.addAttribute("errorMsg", "用户已经被锁定不能登录，请与管理员联系！");
            return "login";
        } catch (AuthenticationException e) {
            token.clear();
            model.addAttribute("errorMsg", "用户或密码不正确！");
            return "login";
        }
    }

    @RequestMapping(value="/loginout",method=RequestMethod.POST)
    public String loginout(@ModelAttribute ASysUser user, Model model){

//        Subject subject = SecurityUtils.getSubject();
//        UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getPassword());
         return "login";
    }

    @RequestMapping("/403")
    public String forbidden(){
        return "403";
    }
}
